# main.py

from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from pathlib import Path
from PIL import Image
import os

# BASE_PATH = Path("/home/ubuntu/SSoftwareFiles/nonebot/xiaomeng-bot/xiaomeng-nonebot/MaiBot/data/emoji")
BASE_PATH = Path("../data/emoji")
THUMBNAIL_DIR = BASE_PATH / "thumbnails"
THUMBNAIL_SIZE = (100, 100)

app = FastAPI()
templates = Jinja2Templates(directory="templates")

# Ensure thumbnail directory exists
THUMBNAIL_DIR.mkdir(exist_ok=True)

def create_thumbnail(image_path: Path):
    thumbnail_path = THUMBNAIL_DIR / image_path.name
    if not thumbnail_path.exists():
        try:
            img = Image.open(image_path)
            img.thumbnail(THUMBNAIL_SIZE)
            img.save(thumbnail_path)
        except Exception as e:
            print(f"Error creating thumbnail for {image_path}: {e}")
    return thumbnail_path

@app.get("/", response_class=HTMLResponse)
async def list_images(request: Request):
    image_files = [f.name for f in BASE_PATH.iterdir() if f.is_file() and f.suffix in ['.jpg', '.jpeg', '.png', '.gif']]
    thumbnails = {name: f"/pic_small/{name}" for name in image_files}
    return templates.TemplateResponse("list_images.html", {"request": request, "images": image_files, "thumbnails": thumbnails})

@app.get("/ls")
async def list_filenames():
    image_files = [f.name for f in BASE_PATH.iterdir() if f.is_file() and f.suffix in ['.jpg', '.jpeg', '.png', '.gif']]
    return {"filenames": image_files}

@app.get("/pic/{image_name}")
async def get_image(image_name: str):
    image_path = BASE_PATH / image_name
    if image_path.is_file():
        return FileResponse(image_path)
    return {"error": "Image not found"}

@app.get("/pic_small/{image_name}")
async def get_thumbnail(image_name: str):
    image_path = BASE_PATH / image_name
    thumbnail_path = create_thumbnail(image_path)
    if thumbnail_path.exists():
        return FileResponse(thumbnail_path)
    return {"error": "Thumbnail not found"}

@app.post("/delete/{image_name}", response_class=HTMLResponse)
async def delete_image(request: Request, image_name: str):
    image_path = BASE_PATH / image_name
    thumbnail_path = THUMBNAIL_DIR / image_name
    if image_path.is_file():
        try:
            os.remove(image_path)
            if thumbnail_path.exists():
                os.remove(thumbnail_path)
            return RedirectResponse(url="/", status_code=303)  # Redirect back to the list
        except Exception as e:
            return templates.TemplateResponse("error.html", {"request": request, "error": f"Error deleting {image_name}: {e}"})
    return templates.TemplateResponse("error.html", {"request": request, "error": f"Image {image_name} not found"})

@app.post("/search", response_class=HTMLResponse)
async def search_image(request: Request, query: str = Form(...)):
    image_files = [
        f.name for f in BASE_PATH.iterdir()
        if f.is_file() and f.suffix in ['.jpg', '.jpeg', '.png', '.gif'] and query.lower() in f.name.lower()
    ]
    thumbnails = {name: f"/pic_small/{name}" for name in image_files}
    return templates.TemplateResponse("list_images.html", {"request": request, "images": image_files, "thumbnails": thumbnails})